package com.ly.algorithm.offerpointer;

/**
 * @Classname Offer16
 * @Description
 *
 * 实现函数double Power(double base, int exponent)，求base的exponent次方。不得使用库函数，同时不需要考虑大数问题。
 *
 * @Date 2021/1/26 19:11
 * @Author 冷心影翼
 */
public class Offer16 {

    public static void main(String[] args) {
        Solution16 solution16 = new Solution16();
        System.out.println(solution16.myPow(2.10000, 3));
        System.out.println(solution16.myPowBinary(2.10000, 3));
    }

}


class Solution16 {

    //超时
    public double myPow(double x, int n) {
        if(n == 0) {
            return 1;
        }
        if(x == 0) {
            return 0;
        }
        double r = 1;
        if(n<0) {
            x = 1/x;
            n = -n;
        }
        for (int i = 1; i <= n; i++) {
            r*=x;
        }
        return r;
    }

    //二分
    public double myPowBinary(double x, int n) {
        if(n == 0) {
            return 1;
        }
        if(x == 0) {
            return 0;
        }
        double r = 1;
        if(n<0) {
            x = 1/x;
            n = -n;
        }
        //n = 1 n = 2
        while (n != 0) {
            if(n%2!=0) {
                r *= x;
            }
            x *= x;
            n /= 2;
        }
        return r;
    }
}